<template>
  <div>
    <form @submit.prevent="submitForm">
      <div class="form-grid">
        <div class="form-row">
          <div class="input-group">
            <label for="recommendStar">推荐星级:</label>
            <input type="number" id="recommendStar" v-model.number="formData.recommendStar" min="-9" max="5" required>
          </div>
          <div class="input-group">
            <label for="localId">本地编号:</label>
            <input type="text" id="localId" v-model="formData.localId">
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label for="supplier">供应商:</label>
            <input type="text" id="supplier" v-model="formData.supplier" required>
          </div>
          <div class="input-group">
            <label for="link">链接:</label>
            <input type="text" id="link" v-model="formData.link" required>
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label for="productName">商品名称:</label>
            <input type="text" id="productName" v-model="formData.productName" required>
          </div>
          <div class="input-group">
            <label>商品图片:</label>
            <UploadPicture :images="formData.productImage" @update:images="handleImagesUpdate" />
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label for="color">颜色:</label>
            <input type="text" id="color" v-model="formData.color">
          </div>
          <div class="input-group">
            <label for="size">尺码:</label>
            <input type="text" id="size" v-model="formData.size">
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label for="productOpinion">评论:</label>
            <input type="text" id="productOpinion" v-model="formData.productOpinion">
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label>代发价格:</label>
            <div class="price-grid">
              <input type="number" v-model.number="formData.price1" step="0.01" placeholder="x1" required>
              <input type="number" v-model.number="formData.price2" step="0.01" placeholder="x2" required>
              <input type="number" v-model.number="formData.price3" step="0.01" placeholder="x3" required>
              <input type="number" v-model.number="formData.price4" step="0.01" placeholder="x4" required>
              <input type="number" v-model.number="formData.price5" step="0.01" placeholder="x5" required>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label>邮费:</label>
            <div class="shipping-grid">
              <input type="number" v-model.number="formData.shipping1" step="0.01" placeholder="x1" required>
              <input type="number" v-model.number="formData.shipping2" step="0.01" placeholder="x2" required>
              <input type="number" v-model.number="formData.shipping3" step="0.01" placeholder="x3" required>
              <input type="number" v-model.number="formData.shipping4" step="0.01" placeholder="x4" required>
              <input type="number" v-model.number="formData.shipping5" step="0.01" placeholder="x5" required>
            </div>
          </div>
        </div>

        <div class="form-row">
          <div class="input-group">
            <label for="relatedDYProductIds">关联商品ID列表 (逗号分隔):</label>
            <input type="text" id="relatedDYProductIds" v-model="formData.relatedDYProductIds" placeholder="例如: 123,456,789">
          </div>
        </div>

        <div class="form-row">
          <button type="submit">{{ isEditMode ? '更新' : '提交' }}</button>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
import UploadPicture from '@/components/UploadPicture.vue';

export default {
  components: {
    UploadPicture,
  },
  data() {
    return {
      formData: {
        recommendStar: 0,
        localId: '',
        supplier: '',
        link: '',
        productName: '',
        productImage: [],
        color: '',
        size: '',
        productOpinion: '',
        price1: 0,
        price2: 0,
        price3: 0,
        price4: 0,
        price5: 0,
        shipping1: 0,
        shipping2: 0,
        shipping3: 0,
        shipping4: 0,
        shipping5: 0,
        relatedDYProductIds: '',
        isEditMode: false,
      }
    };
  },
  created() {
    const productId = this.$route.query.productId;
    if (productId) {
      this.isEditMode = true;
      this.fillProductById(productId);
    } else {
      this.isEditMode = false;
    }
  },
  methods: {
    handleImagesUpdate(newImages) {
      this.formData.productImage = newImages;
    },
    async fillProductById(id) {
      const es_index = 'swin_storage'
      const response = await fetch(`/api/${es_index}/_doc/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      const data = await response.json();
      const product = data._source;
      this.formData = product;
      this.formData.id = id
      console.log('回填表单数据', this.formData)
    },
    async submitForm() {
      try {
        const formData = { ...this.formData };

        const timestamp = Date.now();
        const es_index = 'swin_storage'
        const url = this.isEditMode ? `/api/${es_index}/_doc/${formData.id}?pretty` : `/api/${es_index}/_doc/${timestamp}?pretty`;
        this.formData.createTime = timestamp
        const response = await fetch(url, {
          method: 'PUT',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(formData)
        });

        const data = await response.json();
        if (data._index === es_index) {
          alert('商品保存成功！');
          this.formData = {
            recommendStar: 0,
            localId: '',
            supplier: '',
            link: '',
            productName: '',
            productImage: [],
            color: '',
            size: '',
            productOpinion: '',
            price1: 0,
            price2: 0,
            price3: 0,
            price4: 0,
            price5: 0,
            shipping1: 0,
            shipping2: 0,
            shipping3: 0,
            shipping4: 0,
            shipping5: 0,
            relatedDYProductIds: ''
          };
          this.$router.push('/list');
        } else {
          alert('商品保存失败：' + data.message);
        }
      } catch (error) {
        console.error('提交失败：', error);
        alert('提交失败，请检查网络或后端服务。');
      }
    }
  }
};
</script>

<style scoped>
/* 基本样式 */
body {
  font-family: Arial, sans-serif;
  background-color: #f9f9f9;
  margin: 0;
  padding: 20px;
  color: #333;
}

form {
  max-width: 800px;
  margin: 0 auto;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.form-grid {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-row {
  display: flex;
  gap: 20px;
}

.input-group {
  flex: 1;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: bold;
  color: #555;
}

.input-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

.price-grid,
.shipping-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
}

.price-grid input,
.shipping-grid input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 16px;
  box-sizing: border-box;
}

button[type="submit"] {
  width: 100%;
  padding: 12px;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

button[type="submit"]:hover {
  background-color: #218838;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .form-row {
    flex-direction: column;
  }

  .price-grid,
  .shipping-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 400px) {
  .price-grid,
  .shipping-grid {
    grid-template-columns: 1fr;
  }
}
</style>